package com.hdoit.pisces.web.other.controller;

import java.io.File;
import java.io.FileInputStream;  
import java.io.IOException;  
import java.io.OutputStream;   
import java.util.Hashtable;
import java.util.List;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;  
import javax.servlet.http.HttpServletResponse;  
import org.springframework.stereotype.Controller;  
import org.springframework.ui.Model;  
import org.springframework.web.bind.annotation.RequestMapping;  
import org.springframework.web.bind.annotation.RequestMethod;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.tennetcn.component.web.BaseController;
  
@Controller  
@RequestMapping(value="/admin/qrcode/")  
public class QRCoderController extends BaseController {  
      
	private final String indexViewName="showImage";
	private String path;
	private String content;
    
	@Override
	public String getRoutePath() {
		return "areas/admin/qrcode/";
	}  
	
    @RequestMapping(value=indexViewName,method= {RequestMethod.GET,RequestMethod.POST})  
    public void createFolw(HttpServletRequest request,  
            HttpServletResponse response,Model model,String key) {  
        path = "/opt/apache-tomcat-7.0.79/webapps/resources/"+key+"/qrcode.png";

    	content = "http://119.29.26.204:8080/pisces/admin/xln?num=" +key;
        File file = new File(path);
        FileInputStream fis = null;  
        OutputStream os = null;  
		try {
			if (!file.exists()) {
				Hashtable<EncodeHintType, Object> hts = new Hashtable<EncodeHintType, Object>();
				hts.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L); // 纠错等级
				hts.put(EncodeHintType.CHARACTER_SET, "utf-8"); // 指定编码格式为UTF-8
				try {

					BitMatrix bitMatrix = new MultiFormatWriter().encode(
							content, // 编码内容,编码类型(这里指定为二维码),
							BarcodeFormat.QR_CODE, 300, 300, hts); // 图片宽度,图片高度,设置参数

					MatrixToImageWriter.writeToFile(bitMatrix, "png", file); // 生成的二维码图片

				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			fis = new FileInputStream(path);
			os = response.getOutputStream();
			int count = 0;
			byte[] buffer = new byte[1024 * 8];
			while ((count = fis.read(buffer)) != -1) {
				os.write(buffer, 0, count);
				os.flush();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		try {
			fis.close();
			os.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
    }


	  
}  